package cn.wolfcode.crm.web.controller;


import cn.wolfcode.crm.domain.Department;
import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.domain.Role;
import cn.wolfcode.crm.query.EmployeeQueryObject;

import cn.wolfcode.crm.service.IDepartmentService;
import cn.wolfcode.crm.service.IEmployeeService;
import cn.wolfcode.crm.service.IRoleService;
import cn.wolfcode.crm.util.JsonResult;
import com.fasterxml.jackson.databind.deser.impl.NullsAsEmptyProvider;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/emp")
public class EmployeeController {


    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private IDepartmentService departmentService;
    @Autowired
    private IRoleService roleService;

    @RequestMapping("list")
    @RequiresPermissions(value = {"员工列表权限", "emp:list"}, logical = Logical.OR)
    public String list(@ModelAttribute("qo") EmployeeQueryObject qo, Model model) {
        //员工信息
        PageInfo<Employee> pageInfo = employeeService.selectByQo(qo);
        model.addAttribute("pageInfo", pageInfo);
        //查询员工信息  高级查询
        List<Department> list = departmentService.selectAll();
        model.addAttribute("list", list);
        return "employee/list";

    }

    @RequestMapping("/input")
    @RequiresPermissions(value = {"员工编辑权限", "emp:input"}, logical = Logical.OR)
    public String input(Long empId, Model model) {


        //传过来的id不为null 回显页面   回显员工自己的权限  查找与员工有关联的权限做回显
        if (empId != null) {
            Employee employee = employeeService.selectByEmpId(empId);
            model.addAttribute("emp", employee);
        }
        //查询所有部门信息
        List<Department> departments = departmentService.selectAll();
        model.addAttribute("depts", departments);
        //查询所有角色
        List<Role> roles = roleService.selectAll();
        model.addAttribute("roles", roles);
        return "employee/input";
    }

    @RequestMapping("saveOrUpdate")
    @RequiresPermissions(value = {"员工编辑或新增权限", "emp:saveOrUpdate"}, logical = Logical.OR)
    public String saveOrUpdate(Employee employee, Long[] ids) {

        employeeService.saveOrUpdate(employee, ids);
        return "redirect:/emp/list";
    }

    @RequestMapping("/delete")
    @ResponseBody
    @RequiresPermissions(value = {"员工删除权限", "emp:delete"}, logical = Logical.OR)
    public JsonResult delete(Long empId) {
        JsonResult result = new JsonResult();
        try {
            employeeService.deleteById(empId);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.mark("删除失败");
        }
        return result;
    }

    @RequestMapping("/batchDelete")
    @ResponseBody
    @RequiresPermissions(value = {"员工批量删除权限", "emp:batchDelete"}, logical = Logical.OR)
    public JsonResult batchDelete(Long[] ids) {
        JsonResult result = new JsonResult();
        try {
            employeeService.deleteByIds(ids);
        } catch (Exception e) {
            e.printStackTrace();
            result.mark("删除失败,请重新尝试");
        }
        return result;
    }


    @RequestMapping("/exportXls")
    @RequiresPermissions(value = {"员工导出权限", "emp:exportXls"}, logical = Logical.OR)
    public void exportXls(HttpServletResponse response) {

        //设置下载文件的名称
        response.setHeader("Content-Disposition", "attachment;filename=employee.xls");
        //获取所有员工信息
        List<Employee> employeeList = employeeService.selectAll();

        //将员工信息写入到xls表中 响应给浏览器
        //创建工作簿
        Workbook wb = new HSSFWorkbook();

        //创建表格
        Sheet sheet = wb.createSheet("员工信息表");
        //创建单元行
        Row row = sheet.createRow(0);
        //创建单元格
        row.createCell(0).setCellValue("姓名");
        row.createCell(1).setCellValue("邮箱");
        row.createCell(2).setCellValue("年龄");
        for (int i = 0; i < employeeList.size(); i++) {
            //从获取的全部员工数据中获取数据
            Employee employee = employeeList.get(i);
            //创建行
            Row row1 = sheet.createRow(i + 1);
            row1.createCell(0).setCellValue(employee.getName());
            row1.createCell(1).setCellValue(employee.getEmail());
            row1.createCell(2).setCellValue(employee.getAge());
        }
        //将xls文件写入响应流中
        try {
            wb.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/importXls")
    @ResponseBody
    @RequiresPermissions(value = {"员工导入权限", "emp:importXls"}, logical = Logical.OR)
    public JsonResult importXls(MultipartFile file) {
        JsonResult jsonResult = new JsonResult();

        List<Employee> list = new ArrayList<>();
        try {
            //将文件的输入流传入到(workbook)工作簿中
            HSSFWorkbook wb = new HSSFWorkbook(file.getInputStream());
            //从workbook中获取表格
            HSSFSheet sheet = wb.getSheet("员工信息");
            //获取数据的总行数
            int totalNum = sheet.getLastRowNum();
            for (int i = 0; i < totalNum; i++) {
                //获取每一行
                HSSFRow row = sheet.getRow(i + 1);
                //获取每一行的数据
                String name = row.getCell(0).getStringCellValue();
                String email = row.getCell(1).getStringCellValue();
                double age = row.getCell(2).getNumericCellValue();

                //创建员工对象
                Employee employee = new Employee();
                employee.setName(name);
                employee.setEmail(email);
                employee.setAge((int) age);

                list.add(employee);
            }
            employeeService.insertEmps(list);
            return jsonResult;
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.mark("错误");
        return null;
        }
    }
}
